package top.kaoshanji.p1ch03a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Hashtable;

/**
 * 代码清单-p1ch03a-56页a：更整体化的计数器
 * URL访问地址：/holisticCounter
 * @author kaoshanji
 * ^_^
 * create time 2025/4/2 21:26
 */
public class HolisticCounter extends HttpServlet {

    static int classCount = 0; // 被所有实例共享
    int count = 0; // 分别为每个 servlet
    static Hashtable instances = new Hashtable(); // 也共享

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_PLAIN.toString());
        PrintWriter out = resp.getWriter();

        count++;
        out.println("实例属性被所有servlet共享，Since loading, this servlet instance has been accessed " + count + " times.");

        // 通过设置参数跟踪实例值
        // 散列表中的实例，忽略复制入口
        // size() 方法返回存储的实例数
        instances.put(this, this);
        out.println("静态容器是类属性，所有对象共享，统计类的数量，There are currently " + instances.size() + " instances.");


        classCount++;
        out.println("静态属性是类属性，所有对象共享，每访问一次都递增，Across all instances, this servlet class has been " + "accessed " + classCount + " times.");

    }

}
